package com.example.lib_cache.viewmodel;

import android.content.Context;
import android.util.Log;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.alibaba.fastjson.JSONObject;
import com.example.lib_cache.model.User;
import com.example.lib_cache.network.exception.ApiException;
import com.example.lib_cache.network.exception.ErrorConsumer;
import com.example.lib_cache.network.response.ResponseResultTransformer;
import com.example.lib_cache.service.ApiService;
import com.example.lib_common.util.LiveDataManager;
import com.example.lib_common.util.SpUtils;
import com.netease.nim.uikit.impl.NimUIKitImpl;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class LoginActivityViewModel extends ViewModel {

    public final static String TAG = LoginActivityViewModel.class.getSimpleName();

    private MutableLiveData<String> tokenMutableLiveData;

    private MutableLiveData<User> userMutableLiveData;

    private MutableLiveData<Boolean> result = new MutableLiveData<>();

    public MutableLiveData<Boolean> getResult() {
        return result;
    }

    public void setResult(Boolean result) {
        this.result.postValue(result);
    }
//    private User user;

    public MutableLiveData<User> getUser(){
        return userMutableLiveData;
    }

    public void setUser(User user){
        this.userMutableLiveData = LiveDataManager
                .getInstance().with("user",User.class);
        this.userMutableLiveData.setValue(user);
    }

    public void loginRequest(final ApiService apiService, final Context context,String account,String password){


        final JSONObject requestData = new JSONObject();
        requestData.put("account", account);
        requestData.put("password",password);
        RequestBody requestBody = RequestBody.create
                (MediaType.parse("application/json"), requestData.toString());
        //请求服务器
        apiService.login(requestBody)
                .compose(ResponseResultTransformer.<String>obtain())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Log.d(TAG, "登录成功：" + s);
                        //存取token
                        SpUtils.putString(context,"cctoken",s);
                        //存取全局token
                        tokenMutableLiveData = LiveDataManager
                                .getInstance().with("cctoken",String.class);
                        tokenMutableLiveData.setValue(s);
//                        joinNetease(context);
                        requestIMToken(apiService,context);

                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException ex) {
//                        Log.d(TAG,"错误code"+ex.getCode());
//                        Log.d(TAG,"错误msg"+ex.getErrorMsg());
                    }
                });
    }

    public void requestIMToken(ApiService apiService, final Context context){
        apiService.getIMToken().compose(ResponseResultTransformer.<String>obtain())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        Log.d(TAG,"获取IMToken成功");
                        joinNetease(context,s);
                    }
                }, new ErrorConsumer() {
                    @Override
                    protected void error(ApiException ex) {
                        Log.d(TAG,"获取IMToken失败");
                        Log.d(TAG,"错误code"+ex.getCode());
                        Log.d(TAG,"错误msg"+ex.getErrorMsg());
                    }
                });
    }


    /**
     *  同步网易云信账号系统
     */
    private void joinNetease(final Context context,String imToken){

        LoginInfo info = new LoginInfo(userMutableLiveData.getValue().getAccount()
                ,imToken);
        RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo param) {
                        SpUtils.putString(context,"NIMPassengerToken",param.getToken());
                        SpUtils.putString(context,"NIMPassengerAccount",param.getAccount());
                        NimUIKitImpl.setAccount(param.getAccount());
                        Log.d(TAG,"同步IM即时通信成功");

                    }

                    @Override
                    public void onFailed(int code) {
                        Log.d(TAG,"同步IM即时通信失败");
                    }

                    @Override
                    public void onException(Throwable exception) {
                        Log.d(TAG,"异常："+exception.getMessage());
                    }
                };
        NIMClient.getService(AuthService.class)
                .login(info).setCallback(callback);
        setResult(true);
    }

}
